/** 
 * Copyright 2014 whj All Rights Reserved.
 * 项目名：codegnrt
 * 包名：com.whj.code.dao.mybatis
 * 文件名：RenamePrimaryKeyPlugin.java 
 * 日期：2014-11-25 10:21
 */
package com.whj.code.dao.mybatis;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 重命名主键.
 * @author wanghj
 *
 */
public class RenamePrimaryKeyPlugin extends PluginAdapter{
    private String searchString;
    private String replaceString;
    private Pattern pattern;

    /**
     * 
     */
    public RenamePrimaryKeyPlugin() {
    }

    public boolean validate(List<String> warnings) {

        searchString = properties.getProperty("searchString"); //$NON-NLS-1$
        replaceString = properties.getProperty("replaceString"); //$NON-NLS-1$

        boolean valid = stringHasValue(searchString)
                && stringHasValue(replaceString);

        if (valid) {
            pattern = Pattern.compile(searchString);
        } else {
            if (!stringHasValue(searchString)) {
                warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                        "RenamePrimaryKeyPlugin", //$NON-NLS-1$
                        "searchString")); //$NON-NLS-1$
            }
            if (!stringHasValue(replaceString)) {
                warnings.add(getString("ValidationError.18", //$NON-NLS-1$
                        "RenamePrimaryKeyPlugin", //$NON-NLS-1$
                        "replaceString")); //$NON-NLS-1$
            }
        }

        return valid;
    }

    @Override
    public void initialized(IntrospectedTable introspectedTable) {
        String oldSelectType = introspectedTable.getSelectByPrimaryKeyStatementId();
        Matcher matcher = pattern.matcher(oldSelectType);
        oldSelectType = matcher.replaceAll(replaceString);
        introspectedTable.setSelectByPrimaryKeyStatementId(oldSelectType);

        String oldUpdateType = introspectedTable.getUpdateByPrimaryKeyStatementId();
        matcher = pattern.matcher(oldUpdateType);
        oldSelectType = matcher.replaceAll(replaceString);
        introspectedTable.setUpdateByPrimaryKeyStatementId(oldSelectType);

        String oldDeleteType = introspectedTable.getDeleteByPrimaryKeyStatementId();
        matcher = pattern.matcher(oldDeleteType);
        oldDeleteType = matcher.replaceAll(replaceString);
        introspectedTable.setDeleteByPrimaryKeyStatementId(oldDeleteType);
    }
}
